package com.example.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.activity.Utils.DateUtil;

public class RequestActivity extends AppCompatActivity implements View.OnClickListener {
    private final String msg = "睡了吗?";
    private ActivityResultLauncher<Intent> register;

    @SuppressLint({"MissingInflatedId", "SetTextI18n"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_request);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //
        TextView tv_request = findViewById(R.id.tv_request);
        tv_request.setText("要发送的消息" + msg);
        Button btn_send = findViewById(R.id.btn_send);
        btn_send.setOnClickListener(this);
        //通过register对象进行跳转
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if(result != null && result.getResultCode() == RESULT_OK){
                Intent intent = result.getData();
                if(intent != null){
                    Bundle bundle = intent.getExtras();
                    if(bundle != null){
                        String request_time = bundle.getString("response_time");
                        String request_content = bundle.getString("response_content");
                        String desc = String.format("收到返回消息:\n返回时间:%s\n返回内容:%s", request_time, request_content);
                        TextView tv_back = findViewById(R.id.tv_back);
                        tv_back.setText(desc);
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, ResponseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("request_time", DateUtil.getNowTime());
        bundle.putString("request_content", msg);
        intent.putExtras(bundle);
        register.launch(intent);
    }
}